from copy import deepcopy
from flask import Blueprint, request, jsonify
from controllers.common import *
from controllers.db import *

new_al_legion_event_project_api = Blueprint('new_al_legion_event_project_api', __name__)
new_al_legion_event_project_down_api = Blueprint('new_al_legion_event_project_down_api', __name__)


@new_al_legion_event_project_api.route('/new_al_legion_event_project', methods=['POST'])
def new_al_legion_event_project():
    params = json.loads(request.data)
    action = params['action']
    project = params['project']
    result_data = {'status': 200, 'data': {'msg': '', 'ret': 0, 'type': 'success', 'env': EVN, 'item': ''}}
    if action == 'index':
        query = NewAlLegionEventProject.query.order_by('project').all()
        result = []

        for que in query:
            with open(GLOBAL_PATH + 'new_operation_event.json', encoding='utf-8') as f:
                operation_file = json.load(f)

            basic = json.loads(que.basic)
            doc_id = basic['doc_id'] if 'doc_id' in basic else '-1'
            if doc_id == -1:
                title = '未选择doc_id'
            else:
                for i in operation_file['new_legion_event']:
                    if str(doc_id) == i:
                        if '0' in operation_file['new_legion_event'][i]:
                            title = operation_file['new_legion_event'][i]['0']['title']
                            break
                        else:
                            title = '未配置英文文案'
                    else:
                        title = '未找到对应的doc_id'

            tmp = {
                "project": int(que.project),
                'title': title,
                'remark': str(que.remark)
            }
            result.append(tmp)
        result_data['data']['item'] = result

    elif action == 'clone':
        project_data = NewAlLegionEventProject.query.filter_by(project=project).first()
        new_project_data = NewAlLegionEventProject(
            basic=project_data.basic,
            score_type_list=project_data.score_type_list,
            localization=project_data.localization,
            win_goal_reward=project_data.win_goal_reward,
            lost_goal_reward=project_data.lost_goal_reward,
            rank_reward_user=project_data.rank_reward_user,
            rank_reward_group=project_data.rank_reward_group,
            match_fail_reward=project_data.match_fail_reward,
            remark=project_data.remark
        )
        db.session.add(new_project_data)
        db.session.commit()
        new_project_id = new_project_data.project
        if new_project_id is None:
            result_data['status'] = 500
            result_data['data']['msg'] = "克隆失败"
        else:
            result_data['data']['msg'] = "克隆成功"

    elif action == 'remark':
        remark = str(params['remark'])
        NewAlLegionEventProject.query.filter_by(project=project).update({'remark': remark})
        db.session.commit()
        result_data['data']['msg'] = "备注修改成功"

    elif action == 'delete':
        project_data = NewAlLegionEventProject.query.filter_by(project=project).first()
        db.session.delete(project_data)
        db.session.commit()
        que_project_data = NewAlLegionEventProject.query.filter_by(project=project).first()
        if que_project_data is not None:
            result_data['status'] = 500
            result_data['data']['msg'] = "删除失败"
        else:
            result_data['data']['msg'] = "删除成功"

    elif action == 'detail':
        query = NewAlLegionEventProject.query.filter_by(project=project).first()
        basic = json.loads(query.basic)
        project = query.project
        if 'alliance_member_num' not in basic:
            basic['alliance_member_num'] = 20
        if 'alliance_create_time' not in basic:
            basic['alliance_create_time'] = 604800
        if 'al_legion_top_limit' not in basic:
            basic['al_legion_top_limit'] = 40
        if 'al_legion_min_member_num' not in basic:
            basic['al_legion_min_member_num'] = 5
        if 'al_legion_max_member_num' not in basic:
            basic['al_legion_max_member_num'] = 40

        # if 'calendar_doc' not in basic:
        #     basic['calendar_doc'] = 1

        if '_tag' not in basic:
             basic['_tag'] = []

        basic['project'] = project

        with open(STATIC_PATH + 'new_al_legion_event_task_pool.json', encoding='utf-8') as f:
            content = json.load(f)
        task_pool = []
        for score_node in content:
            task_pool.append(
                {'value': score_node['idx'],
                 'label': '{0}-{1}'.format(
                    score_node['idx'], score_node['label'])}
            )

        with open(GLOBAL_PATH + 'new_operation_event.json', encoding='utf-8') as f:
            operation_file = json.load(f)
        doc_id_list = []
        for i in operation_file['new_legion_event']:
            if '0' in operation_file['new_legion_event'][i]:
                doc_id_list.append({
                    'value': int(i),
                    'label': '%s - %s' % (int(i), operation_file['new_legion_event'][i]['0']['title'])
                })

        tmp = {
            "project": project,
            'basic': basic,
            'score_type_list': json.loads(query.score_type_list),
            'win_goal_reward': json.loads(query.win_goal_reward),
            'lost_goal_reward': json.loads(query.lost_goal_reward),
            'rank_reward_user': json.loads(query.rank_reward_user),
            'rank_reward_group': json.loads(query.rank_reward_group),
            'match_fail_reward': json.loads(query.match_fail_reward),
            'task_pool': task_pool,
            'doc_id_list': doc_id_list
        }
        result_data['data']['item'] = tmp

    elif action == 'update_part':
        data = params['data']
        part = params['part']

        if part == 'basic':
            NewAlLegionEventProject.query.filter_by(project=project).update({
                'basic': json.dumps(data)
            })

        elif part == 'score_type':
            NewAlLegionEventProject.query.filter_by(project=project).update({
                'score_type_list': json.dumps(data['score_type_list'])
            })

        elif part == 'win_goal_reward':
            NewAlLegionEventProject.query.filter_by(project=project).update({
                'win_goal_reward': json.dumps(data)
            })

        elif part == 'lost_goal_reward':
            NewAlLegionEventProject.query.filter_by(project=project).update({
                'lost_goal_reward': json.dumps(data)
            })

        elif part == 'rank_reward_user':
            NewAlLegionEventProject.query.filter_by(project=project).update({
                'rank_reward_user': json.dumps(data)
            })

        elif part == 'rank_reward_group':
            NewAlLegionEventProject.query.filter_by(project=project).update({
                'rank_reward_group': json.dumps(data)
            })

        elif part == 'match_fail_reward':
            NewAlLegionEventProject.query.filter_by(project=project).update({
                'match_fail_reward': json.dumps(data)
            })

        db.session.commit()
        result_data['data']['msg'] = "更新成功"

    return jsonify(result_data)


@new_al_legion_event_project_down_api.route('/new_al_legion_event_project_down/<int:is_push>', methods=['GET', 'POST'])
def new_al_legion_event_project_down(is_push):
    result = {}
    query = NewAlLegionEventProject.query.order_by('project').all()

    with open(STATIC_PATH + 'new_al_legion_event_task_pool.json', encoding='utf-8') as f:
        task_pool = json.load(f)

    for que in query:
        pid = que.project
        basic = json.loads(que.basic)
        score_type_list = json.loads(que.score_type_list)
        # localization = json.loads(que.localization)
        win_goal_reward = json.loads(que.win_goal_reward)
        rank_reward_user = json.loads(que.rank_reward_user)
        rank_reward_group = json.loads(que.rank_reward_group)
        match_fail_reward = json.loads(que.match_fail_reward)

        calc_score = {'score_type_list': []}
        for score_id in score_type_list:
            for task_node in task_pool:
                if score_id == task_node['idx']:
                    hide = task_node['hide'] if 'hide' in task_node else 1
                    rule_target = task_node['rule_target'] if 'rule_target' in task_node else 0
                    rule_type = task_node['rule_type'] if 'rule_type' in task_node else 0
                    score_tmp = {
                        'type': task_node['type'],
                        'id_list': task_node['id_list'],
                        'lv_list': task_node['lv_list'],
                        'id_class': task_node['id_class'],
                        'doc_id': task_node['doc_id'],
                        'num_unit': task_node['num_unit'],
                        'show': task_node['show'],
                        'hide': hide,
                        'class': task_node['class'],
                        'num': task_node['num'],
                        'score': task_node['score'],
                        'task_id': task_node['task_id'],
                        'target': task_node['target'],
                        'rule_target': rule_target,
                        'rule_type': rule_type,
                    }
                    calc_score['score_type_list'].append(score_tmp)
                    break
        calc_score['score_type_list'].append(
            {"class": 1, "doc_id": 1, "hide": 1, "id_class": 0, "id_list": [-1], "lv_list": [-1], "num": 1,
             "num_unit": 1, "rule_target": [0], "rule_type": 0, "score": 1, "show": [], "target": 0, "task_id": 0,
             "type": 9001})
        calc_score['score_type_list'].append(
            {"class": 1, "doc_id": 1, "hide": 1, "id_class": 0, "id_list": [-1], "lv_list": [-1], "num": 1,
             "num_unit": 1, "rule_target": [0], "rule_type": 0, "score": 1, "show": [], "target": 0, "task_id": 0,
             "type": 9002})
        calc_score['score_type_list'].append(
            {"class": 1, "doc_id": 1, "hide": 1, "id_class": 0, "id_list": [-1], "lv_list": [-1], "num": 1,
             "num_unit": 1, "rule_target": [0], "rule_type": 0, "score": 1, "show": [], "target": 0, "task_id": 0,
             "type": 9003})

        for node in rank_reward_user:
            node['reward'] = RewardToTMysqlNew(node['reward'])
            node['doc_id'] = 1

        group = [
            {'from': rank_reward_group['win_from'],
             'to': rank_reward_group['win_to'],
             'reward': RewardToTMysqlNew(rank_reward_group['win_reward']),
             'doc_id': 1},
            {'from': rank_reward_group['lost_from'],
             'to': rank_reward_group['lost_to'],
             'reward': RewardToTMysqlNew(rank_reward_group['lost_reward']),
             'doc_id': 1}
        ]

        win_reward = []
        lose_reward = []

        for node in win_goal_reward:
            win_reward.append({
                "from": 1,
                "to": node['to'],
                "reward": RewardToTMysqlNew(node['reward']),
                "doc_id": 1
            })
            lose_reward.append({
                "from": 1,
                "to": node['to'],
                "reward": RewardToTMysqlNew(node['lose_reward']),
                "doc_id": 1
            })

        new_match_fail_reward = RewardToTMysqlNew(match_fail_reward)

        # calendar_doc = basic['calendar_doc'] if 'calendar_doc' in basic else 1
        calendar_doc = basic['doc_id']
        top_reward = RewardToTMysqlNew(basic['top_reward'])

        _tag = basic['_tag'] if '_tag' in basic else []

        result[str(pid)] = {
            '_tag': _tag,
            'calendar_conf': {
                'event_type': 118,
                'event_ui': 1,
                'order': 1,
                'jump': 1,
                'localization': {
                    'title': calendar_doc,
                    'info': calendar_doc
                },
                'reward': top_reward,
                'show_type': 0
            },
            'basic': {
                'event_ui': basic['event_ui']
            },
            'localization_str': {},
            'localization_doc': {
                'title': basic['doc_id'],
                'info': basic['doc_id'],
                'content': basic['doc_id']
            },
            'calc_score': calc_score,
            'castle_lv': basic['castle_lv'],
            'reward': {
                'rank_reward': {
                    'user': rank_reward_user,
                    'group': group
                },
                'win_goal_reward': {
                    'user': win_reward
                },
                'lost_goal_reward': {
                    'user': lose_reward
                },
                'match_fail_reward': {
                    'group': {
                        'reward': new_match_fail_reward,
                        'doc_id': 1
                    }
                }
            },
            'extern0': {
                'al_legion_max_member_num': basic['al_legion_max_member_num'],
                'al_legion_min_member_num': basic['al_legion_min_member_num'],
                'al_legion_top_limit': basic['al_legion_top_limit'],
                'al_legion_min_force': basic['al_legion_min_force'],
                'alliance_create_time': basic['alliance_create_time'],
                'alliance_member_num': basic['alliance_member_num'],
                "top_reward": top_reward
            },
            'extern1': {},
            'remark': que.remark
        }

    sign_up_result = deepcopy(result)
    for v in sign_up_result.values():
        del v['calendar_conf']

    response = DownLoad('new_al_legion_event_sign_up_project', sign_up_result, is_push)
    response = DownLoad('new_al_legion_event_project', result, is_push)

    return response
